<?php
namespace app\jobmanagement\service;

use think\Db;
use think\Model;

use app\model\TaskWork as TaskWorkModel;
use app\model\TaskTask as TaskTaskModel;
use app\model\Settle as SettleModel;
use app\model\Product as ProductModel;
use app\model\ProductWork as ProductWorkModel;
use app\model\User as UserModel;
use app\model\Capital as CapitalModel;

use app\lib\Dingtalk as DingtalkLib;

use app\jobmanagement\service\Common as CommonService;

class Settle extends Model
{
    public $dd_user_id;

    public $mTask;

    public $mTaskWork;

    public $mSettle;

    public $task_status;

    public $settle_status;

    public $is_sys;

    public $dept_id;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->dd_user_id = session('dd_user_id');
        $this->mTask = new TaskTaskModel();
        $this->mTaskWork = new TaskWorkModel();
        $this->mSettle = new SettleModel();
        $this->task_status = config('dic.task_status');
        $this->settle_status = config('dic.settle_status');
        $this->is_sys = session('is_sys');
        $this->dept_id = session('dept_id');
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 9:31
     * @description 获取结算单相关参数
     * @param $type 类型 1 待审核结算单 2 全部结算单 3 我的结算单
     * @return array|array[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSettleListParam($type)
    {
        $settle_status = $this->settle_status;
        $settle_status_box = [];
        foreach ($settle_status as $key => $val) {
            $settle_status_box[] = ['status_id' => $key, 'status_name' => $val];
        }
        // 区分部门
        $add_where = [];
        if (!$this->is_sys && $this->dept_id) {
            $add_where['dept_id'] = $this->dept_id;
        }
        switch ($type) {
            case 1:
                // 待审核结算单
                // 区分用户等级给予不同的参数
                $mUser = new UserModel();
                $user_info = $mUser->where(['dd_user_id' => $this->dd_user_id])->find();
                if (!empty($user_info) && $user_info['level'] == 2) {
                    $select['settle_status'] = 2;
                    $select['leader'] = $this->dd_user_id;
                } else {
                    $select['settle_status'] = 3;
                }
                $status_box = [];
                $user = $this->mSettle
                    ->where($select)
                    ->where($add_where)
                    ->field('create_user')
                    ->group('create_user')
                    ->select();
                if (empty($user)) {
                    return ['user' => [], 'status' => $status_box];
                }
                $user_box = [];
                foreach ($user as $one) {
                    $user_box[] = ['user_id' => $one['create_user'], 'user_name' => get_user_name($one['create_user'])];
                }
                return ['user' => $user_box, 'status' => $status_box];
                break;
            case 2:
                // 所有结算单
                $user = $this->mSettle
                    ->field('create_user')
                    ->group('create_user')
                    ->where($add_where)
                    ->select();
                $user_box = [];
                foreach ($user as $one) {
                    $user_box[] = ['user_id' => $one['create_user'], 'user_name' => get_user_name($one['create_user'])];
                }
                return ['user' => $user_box, 'status' => $settle_status_box];
                break;
            case 3:
                // 我的结算单
                return ['user' => [], 'status' => $settle_status_box];
            break;
            default:
                return ['user' => [], 'status' => []];
                break;
        }

    }


    /**
     * @auther zlq
     * @create_time 2020/5/20 10:05
     * @description
     * @param $type 类型 1 待审核任务单 2 所有任务单 3 我提交的任务单
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSettleListByType($type, $param)
    {
        // 处理筛选参数
        $settle_status = $this->settle_status;
        $select = [];
        if (isset($param['status']) && $param['status']) {
            $select['settle_status'] = $param['status'];
        }
        if (isset($param['user']) && $param['user']) {
            $select['create_user'] = $param['user'];
        }
        if (isset($param['date']) && $param['date']) {
            $select['create_time'] = ['like', $param['date'].'%'];
        }
        $param['page'] = $param['page'] > 1 ? $param['page'] : 1;
        $page_size = PAGE_SIZE;
        $offset = ($param['page'] - 1) * $page_size;
        // 区分部门
        $add_where = [];
        if (!$this->is_sys && $this->dept_id) {
            $add_where['dept_id'] = $this->dept_id;
        }
        switch ($type) {
            case 1:
                // 待审核任务单
                $mUser = new UserModel();
                $user_info = $mUser->where(['dd_user_id' => $this->dd_user_id])->find();
                if (!empty($user_info) && $user_info['level'] == 2) {
                    $select['settle_status'] = 2;
                    $select['leader'] = $this->dd_user_id;
                } else {
                    $select['settle_status'] = 3;
                }
                $settle_list = $this->mSettle
                    ->where($select)
                    ->where($add_where)
                    ->limit($offset, $page_size)
                    ->order('id desc')
                    ->select();
                break;
            case 2:
                // 所有任务单
                $settle_list = $this->mSettle
                    ->where($select)
                    ->where($add_where)
                    ->limit($offset, $page_size)
                    ->order('id desc')
                    ->select();
                break;
            case 3:
                // 我提交的任务单
                $select['create_user'] = $this->dd_user_id;
                $settle_list = $this->mSettle
                    ->where($select)
                    ->limit($offset, $page_size)
                    ->order('id desc')
                    ->select();
                break;
            default:
                return [];
        }
        // 处理任务单相关显示
        if (empty($settle_list)) {
            return [];
        } else {
            $box = [];
            $mTask = $this->mTask;
            $mTaskWork = $this->mTaskWork;
            foreach ($settle_list as $key => $item) {
                $temp = $item->toArray();
                $temp['settle_status_name'] = $settle_status[$item['settle_status']];
                $temp['create_user'] = get_user_name($item['create_user']);
                // 获取任务名称
                $temp_task = $mTask->where(['id' => $temp['task_id']])->find();
                $temp_task_work = $mTaskWork->where(['id' => $temp['work_id']])->find();
                $temp['task_date'] = isset($temp_task['task_date']) ? $temp_task['task_date'] : '已删除';
                $temp['prod_name'] = isset($temp_task['prod_name']) ? $temp_task['prod_name'] : '已删除';
                $temp['prod_number'] = isset($temp_task['prod_number']) ? floatval($temp_task['prod_number']) : '已删除';
                $temp['prod_unit'] = isset($temp_task['prod_unit']) ? $temp_task['prod_unit'] : '已删除';
                $temp['work_name'] = isset($temp_task_work['name']) ? $temp_task_work['name'] : '已删除';
                $box[] = $temp;
            }
            return $box;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 11:15
     * @description 获取结算单详情
     * @param int $settle_id 结算单ID
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSettleInfo($settle_id = 0)
    {
        $settle_status = $this->settle_status;
        if (!$settle_id) {
            return [];
        }
        $settle = $this->mSettle
            ->where(['id' => $settle_id])
            ->find();
        if (empty($settle)) {
            return [];
        }
        $settle = $settle->toArray();
        $settle['settle_status_name'] = $settle_status[$settle['settle_status']];
        $settle['create_user'] = get_user_name($settle['create_user']);
        // 处理相关信息
        return $settle;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 11:32
     * @description 查询某任务单及对应工种
     * @param int $task_id 任务单ID
     * @param int $work_id 任务单工种ID
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSettleTaskInfo($task_id = 0, $work_id = 0)
    {
        if (!$task_id) {
            return [];
        }
        $task = $this->mTask
            ->where(['id' => $task_id])
            ->find();
        if (empty($task)) {
            return [];
        }
        $task['prod_number'] = floatval($task['prod_number']);
        $task = $task->toArray();
        $task_work = $this->mTaskWork
            ->where(['id' => $work_id])
            ->find();
        if (empty($task_work)) {
            return [];
        }
        $task_box['id'] = $task['id'];
        $task_box['task_code'] = $task['task_code'];
        $task_box['prod_name'] = $task['prod_name'];
        $task_box['prod_amount'] = $task['prod_amount'];
        $task_box['prod_unit'] = $task['prod_unit'];
        $task_box['prod_number'] = floatval($task['prod_number']);
        $task_box['work_name'] = $task_work['name'];
        $task_box['proportion'] = $task_work['proportion'];
        $task_box['amount'] = $task['task_amount'];
        $task_box['work_amount'] = $task_work['amount'];
        $task_box['worker_amount'] = $task_work['worker_amount'];
        // 处理相关信息 - 工种包含员工
        $worker = explode('-', trim($task_work['worker'], '-'));
        $temp = [];
        if (empty($worker)) {
            $temp = [];
        } else {
            foreach ($worker as $item) {
                $temp[] = [
                    'worker_id' => $item,
                    'worker_name' => get_user_name($item),
                    'is_select' => $this->dd_user_id == $item ? 1 : 0
                ];
            }
        }
        $task_box['worker'] = $temp;
        return $task_box;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 14:17
     * @description 通过结算单审核
     * @param int $settle_id 结算单Id
     * @param string $remark 备注
     * @return array|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function settleAuditCheckPass($settle_id = 0, $remark = '')
    {
        if (!$settle_id) {
            return -1;
        }
        $settle = $this->mSettle
            ->where(['id' => $settle_id])
            ->find();
        if (empty($settle)) {
            return -2;
        }
        $time = date('Y-m-d H:i:s');
        $user_name = get_user_name($this->dd_user_id);
        $DingTalkService = new DingtalkLib();
        switch ($settle['settle_status']) {
            case 2:
                // 待结算审核-组长
                if ($settle['leader'] != $this->dd_user_id) {
                    return -10;
                }
                if ($remark) {
                    $tip = $user_name . '于' . $time .'审核通过结算单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time .'审核通过结算单;';
                }
                $update = [
                    'settle_status' => 3,
                    'status_remark' =>  $settle['status_remark'] . $tip
                ];
                $res = $this->mSettle
                    ->where(['id' => $settle_id])
                    ->update($update);
                if ($res) {
                    $msg_send = $DingTalkService->sendNoticeMessage($settle['create_user'], $tip);
                    addLog($tip, 2, $settle_id, $user_name);
                    return 1;
                } else {
                    return 0;
                }
                break;
            case 3:
                // 待提现审核
                if ($remark) {
                    $tip = $user_name . '于' . $time .'审核通过结算单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time .'审核通过结算单;';
                }
                $tip2 = $user_name . '于' . $time .'审核通过结算单;增加金额' . $settle['amount'];
                $update = [
                    'settle_status' => 4,
                    'status_remark' => $settle['status_remark'] . $tip
                ];
                // 获取用户信息
                $mUser = new UserModel();
                $mCapital = new CapitalModel();
                // 判断该钉钉用户本地中是否存在
                $user = $mUser->where(['dd_user_id' => $settle['create_user']])->find();
                if (empty($user)) {
                    return -11;
                }
                // 关闭验证用户账号信息
                // if (empty($user['account_code']) || empty($user['account_user'])) {
                //    return -12;
                //}
                // 添加用户资金记录
                $capital = [
                    'dd_user_id' => $settle['create_user'],
                    'type' => 1,
                    'amount' => $settle['amount'],
                    'account_user' => $user['account_user'],
                    'account_code' => $user['account_code'],
                    'status' => 3,
                    'create_time' => $time,
                    'create_user' => $this->dd_user_id,
                    'update_remark' => "工作任务结算入账",
                    'status_remark' => $tip2,
                ];
                $capital_amount = $user['capital'] + $settle['amount'];
                try {
                    Db::startTrans();
                    $res_settle = $this->mSettle
                        ->where(['id' => $settle_id])
                        ->update($update);
                    $res_capital = $mCapital->insert($capital);
                    $res_user = $mUser->where(['dd_user_id' => $settle['create_user']])->update(['capital' => $capital_amount]);
                    if ($res_settle && $res_capital && $res_user) {
                        Db::commit();
                        $msg_send = $DingTalkService->sendNoticeMessage($settle['create_user'], $tip);
                        addLog($tip, 2, $settle_id, $user_name);
                        return 1;
                    } else {
                        Db::rollback();
                        return 0;
                    }
                    // 添加资金资金记录
                } catch (\Exception $exception) {
                    dump($exception->getMessage());
                    Db::rollback();
                    return 0;
                }
                break;
            default:
                return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 14:22
     * @description 审核退回结算单
     * @param int $settle_id 结算单ID
     * @param string $remark 备注
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function settleAuditCheckRefuse($settle_id = 0, $remark = '')
    {
        if (!$settle_id) {
            return -1;
        }
        $settle = $this->mSettle
            ->where(['id' => $settle_id])
            ->find();
        if (empty($settle)) {
            return -2;
        }
        $time = date('Y-m-d H:i:s');
        $user_name = get_user_name($this->dd_user_id);
        $DingTalkService = new DingtalkLib();
        switch ($settle['settle_status']) {
            case 2:
                // 待结算审核-组长
                if ($remark) {
                    $tip = $user_name . '于' . $time . '审核退回确认结算单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time . '审核退回确认结算单;';
                }
                $update = [
                    'settle_status' => 1,
                    'status_remark' => $settle['status_remark'] . $tip
                ];
                $res = $this->mSettle
                    ->where(['id' => $settle_id])
                    ->update($update);
                $msg_send = $DingTalkService->sendNoticeMessage($settle['create_user'], $tip);
                break;
            case 3:
                // 待结算审核-管理
                if ($remark) {
                    $tip = $user_name . '于' . $time . '审核退回确认结算单,备注:' . $remark . ';';
                } else {
                    $tip = $user_name . '于' . $time . '审核退回确认结算单;';
                }
                $update = [
                    'settle_status' => 2,
                    'status_remark' => $settle['status_remark'] . $tip
                ];
                $res = $this->mSettle
                    ->where(['id' => $settle_id])
                    ->update($update);
                $msg_send = $DingTalkService->sendNoticeMessage($settle['create_user'], $tip);
                break;
            default:
                return 0;
        }
        if ($res) {
            addLog($tip, 2, $settle_id, $user_name);
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 15:10
     * @description 工人提交结算申请
     * @param int $settle_id 结算单ID
     * @param string $remark 备注
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function workerApplySettle($settle_id = 0, $remark = '')
    {
        if (!$settle_id) {
            return -1;
        }
        $settle = $this->mSettle
            ->where(['id' => $settle_id])
            ->find();
        if (empty($settle)) {
            return -2;
        }
        if ($settle['settle_status'] != 1) {
            return -3;
        }
        $now_time = date('Y-m-d H:i:s');
        $now_user = $this->dd_user_id;
        if ($now_user != $settle['create_user']) {
            return -4;
        }
        $mUser = new UserModel();
        $user = $mUser->where(['dd_user_id' => $now_user])->find();
        if (empty($user)) {
            return -5;
        }
        // 关闭结算单申请验证账号
        // if (!$user['account_code']) {
        //    return -6;
        // }

        $tip = $user['name'] . '于' . $now_time . '申请校验结算单;';
        $update = [
            'settle_status' => 2,
            'remark' => $remark,
            'status_remark' => $settle['status_remark'] . $tip
        ];
        $res = $this->mSettle->where(['id' => $settle_id])->update($update);
        addLog($tip, 2, $settle_id, $now_user);
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }
}